import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

// 白名单, 如果点击返回的时候的页面是这些 就会调用关闭网页返回程序
const CATCH_URLS = ['m.ctrip.com/', 'm.ctrip.com/html5/', 'm.ctrip.com/html5'];

/// 和H5交互的封装webview
class WebView extends StatefulWidget {
  final String url;
  final String statusBarColor;
  final String title;
  final bool hideAppbar;
  final bool backForbid;

  WebView(
      {this.url,
      this.statusBarColor,
      this.title,
      this.hideAppbar,
      this.backForbid = false});

  @override
  _WebViewState createState() => _WebViewState();
}

class _WebViewState extends State<WebView> {
  final webviewReference = FlutterWebviewPlugin();
  StreamSubscription<String> _onUrlChanged;
  StreamSubscription<WebViewStateChanged> _onStateChanged;
  StreamSubscription<WebViewHttpError> _onLoadErr;
  bool exiting = false;

  @override
  void initState() {
    super.initState();
    webviewReference.close();
    // 注册监听url的变化
    _onUrlChanged = webviewReference.onUrlChanged.listen((String url) {});
    // 状态变化的监听
    _onStateChanged =
        webviewReference.onStateChanged.listen((WebViewStateChanged state) {
      switch (state.type) {
        case WebViewState.startLoad:

          /// 判断是不是属于白名单, 并且未返回的情况
          /// 属于的话判断是否禁止返回
          /// 禁止的话加载当前url
          /// 否则返回上级, 这个标志位应该是为了防止重复触发
          if (_isToMain(state.url) && !exiting) {
            if (widget.backForbid) {
              webviewReference.launch(widget.url);
            } else {
              Navigator.pop(context);
              exiting = true;
            }
          }
          break;
        default:
          break;
      }
    });
    // 对网页加载错误的处理
    _onLoadErr = webviewReference.onHttpError.listen((WebViewHttpError error) {
      print(error);
    });
  }

  // 检查url是不是属于白名单
  _isToMain(String url) {
    bool contain = false;
    for (final v in CATCH_URLS) {
      if (url?.endsWith(v) ?? false) {
        contain = true;
        break;
      }
      return contain;
    }
  }

  @override
  void dispose() {
    _onUrlChanged.cancel();
    _onStateChanged.cancel();
    _onLoadErr.cancel();
    webviewReference.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String statusBarColorStr = widget.statusBarColor ?? 'ffffff';
    Color backBtnColor;
    statusBarColorStr == 'ffffff'
        ? backBtnColor = Colors.black
        : backBtnColor = Colors.white;

    return Scaffold(
      body: Column(
        children: <Widget>[
          // 自定义的appbar
          _appBar(Color(int.parse('0xff' + statusBarColorStr)), backBtnColor),
          Expanded(
            //撑满的网页
            child: WebviewScaffold(
              url: widget.url,
              hidden: false,
              withLocalStorage: true,
              withZoom: false,
              initialChild: Container(
                color: Colors.white,
                child: Center(
                  child: Text('loading'),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  // 自定义appbar
  _appBar(Color backgroundColor, Color backButtonColor) {
    if (widget.hideAppbar ?? false) {
      return Container(
        color: backgroundColor,
        height: 30,
      );
    }
    return Container(
      color: backgroundColor,
      padding: EdgeInsets.fromLTRB(0, 40, 0, 10),
      child: FractionallySizedBox(
        // 让元素充满屏幕
        widthFactor: 1, // 宽度充满
        child: Stack(
          children: <Widget>[
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              // 第一个元素 是返回按钮
              child: Container(
                margin: EdgeInsets.fromLTRB(0, 40, 0, 10),
                child: Icon(
                  Icons.close,
                  size: 26,
                  color: backButtonColor,
                ),
              ),
            ),
            Positioned(
              left: 0,
              right: 0,
              child: Text(
                widget.title ?? '',
                style: TextStyle(fontSize: 20, color: backButtonColor),
              ),
            )
          ],
        ),
      ),
    );
  }
}
